@writedocs/generator 0.10.15 → 0.10.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.10.15",
3
+ "version": "0.10.16",
4
4
  "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -42,8 +42,15 @@ export function writeRedirectsFile(distDir, contentDir) {
42
42
  // see redirectSchema's comment in lib/config.ts on why the schema itself
43
43
  // has no field for one - a redirect a site author deliberately
44
44
  // configured is safe to treat as permanent).
45
+ // Each address in both forms, with and without the trailing slash:
46
+ // `_redirects` matches the path as it was requested, and a rule for
47
+ // "/old" alone left "/old/" to the fallback page - a 200, not a 301.
48
+ // An address the site lists itself keeps its own destination.
49
+ const listed = new Set(redirects.map((r) => r.source));
45
50
  for (const { source, destination } of redirects) {
46
51
  lines.push(`${source} ${destination} 301`);
52
+ const other = otherSlashForm(source);
53
+ if (other && !listed.has(other)) lines.push(`${other} ${destination} 301`);
47
54
  }
48
55
  // Generated API pages that changed address (lib/moved-api-pages.js) -
49
56
  // after the site's own, which win for the same address (first match).
@@ -102,6 +109,15 @@ export function writeRedirectsFile(distDir, contentDir) {
102
109
  fs.writeFileSync(redirectsPath, existing + generated);
103
110
  }
104
111
 
112
+ /** "/old" for "/old/" and the reverse - null for the root, and for an
113
+ * address that names a file ("/feed.xml"), which has one form only. */
114
+ export function otherSlashForm(source) {
115
+ if (typeof source !== 'string' || source === '/' || !source.startsWith('/')) return null;
116
+ if (source.endsWith('/')) return source.slice(0, -1) || null;
117
+ if (/\.[a-z0-9]+$/i.test(source.split('/').pop())) return null;
118
+ return `${source}/`;
119
+ }
120
+
105
121
  /** Astro's pages for temporary redirects below the site's root, as
106
122
  * `{ url: "/docs/creator/", target }`. */
107
123
  function temporaryRedirectPages(distDir) {
@@ -42,8 +42,9 @@ const titleId = _titleId ?? slugify(plainText(title));
42
42
  <span class="wd-accordion-text">
43
43
  <span class="wd-accordion-title" id={titleId}>
44
44
  {Astro.slots.has("wd-title") ? <slot name="wd-title" /> : title}
45
- <a class="wd-heading-anchor" href={`#${titleId}`} aria-label="Link to this section"> # </a>
45
+ <a class="wd-heading-anchor" href={`#${titleId}`} aria-label="Link to this section" data-markdown-ignore> # </a>
46
46
  </span>
47
+ {" "}
47
48
  {description && <span class="wd-accordion-description">{description}</span>}
48
49
  </span>
49
50
  </span>
@@ -64,7 +64,7 @@ const titleId = title ? (_titleId ?? slugify(plainText(title))) : undefined;
64
64
  title && (
65
65
  <div class="wd-callout-title" id={titleId}>
66
66
  {titleHtml ? <Fragment set:html={titleHtml} /> : title}
67
- <a class="wd-heading-anchor" href={`#${titleId}`} aria-label="Link to this section">
67
+ <a class="wd-heading-anchor" href={`#${titleId}`} aria-label="Link to this section" data-markdown-ignore>
68
68
  #
69
69
  </a>
70
70
  </div>
@@ -127,7 +127,7 @@ const single = !showCopy && items.length === 1 ? items[0] : null;
127
127
  const hasDropdown = items.length > 0 && !single;
128
128
  ---
129
129
  {(showCopy || items.length > 0) && (
130
- <div class="wd-copy-page-split" data-pagefind-ignore="all">
130
+ <div class="wd-copy-page-split" data-pagefind-ignore="all" data-markdown-ignore>
131
131
  {showCopy && (
132
132
  <button type="button" class:list={['wd-copy-page-primary', { 'wd-copy-page-alone': !hasDropdown }]} data-copy-page data-md-path={mdPath} aria-label="Copy page as Markdown">
133
133
  <Icon name="lucide:copy" class="wd-copy-page-icon" />
@@ -41,12 +41,17 @@ const hasDefault = defaultValue !== undefined && defaultValue !== null && defaul
41
41
 
42
42
  <div class:list={["wd-parameter", { "wd-parameter-deprecated": deprecated }, extraClasses(Astro.props)]}>
43
43
  <div class="wd-parameter-head">
44
- {pre.map((label) => <span class="wd-parameter-label">{label}</span>)}
45
- <span class="wd-parameter-name">{name}</span>
46
- {type && <span class="wd-parameter-type">{type}</span>}
47
- {required && <span class="wd-parameter-required">required</span>}
48
- {deprecated && <span class="wd-parameter-deprecated-badge">deprecated</span>}
49
- {post.map((label) => <span class="wd-parameter-label">{label}</span>)}
44
+ {
45
+ /* A space after each piece: the row is laid out by its flex gap, but read
46
+ as text - by a screen reader, a copy, an AI agent - "amount integer
47
+ required" must not run together as "amountintegerrequired". */
48
+ }
49
+ {pre.map((label) => <Fragment><span class="wd-parameter-label">{label}</span>{" "}</Fragment>)}
50
+ <span class="wd-parameter-name">{name}</span>{" "}
51
+ {type && <Fragment><span class="wd-parameter-type">{type}</span>{" "}</Fragment>}
52
+ {required && <Fragment><span class="wd-parameter-required">required</span>{" "}</Fragment>}
53
+ {deprecated && <Fragment><span class="wd-parameter-deprecated-badge">deprecated</span>{" "}</Fragment>}
54
+ {post.map((label) => <Fragment><span class="wd-parameter-label">{label}</span>{" "}</Fragment>)}
50
55
  {hasDefault && <span class="wd-parameter-default">default: {String(defaultValue)}</span>}
51
56
  </div>
52
57
  <div class="wd-parameter-body">
@@ -8,4 +8,14 @@ interface Props {
8
8
  }
9
9
  const { for: audience = 'humans' } = Astro.props as Props;
10
10
  ---
11
- {audience !== 'agents' && <slot />}
11
+ {
12
+ /* What only people see is marked as such: the page's Markdown copy leaves it
13
+ out (lib/visibility.js), and `data-markdown-ignore` tells a tool comparing
14
+ the two that it's meant to. `display: contents`, so the wrapper changes
15
+ nothing about the layout of what's inside. */
16
+ }
17
+ {audience !== 'agents' && (
18
+ <span data-markdown-ignore style="display: contents">
19
+ <slot />
20
+ </span>
21
+ )}
@@ -77,6 +77,9 @@ import AnalyticsScripts from "./components/AnalyticsScripts.astro";
77
77
  import AskAiWidget from "./components/AskAiWidget.astro";
78
78
  import ConsentBanner from "./components/ConsentBanner.astro";
79
79
  import { seoHead, hreflangLinks } from "../lib/seo-tags.js";
80
+ import { fontStack, fallbackFontFaces } from "../lib/font-fallback.js";
81
+ import { htmlDirective } from "../lib/agent-directive.js";
82
+ import { contextMenuOptions } from "../lib/config";
80
83
  import { jsonLd, serializeJsonLd } from "../lib/json-ld.js";
81
84
  import { consentOptions } from "../lib/consent.js";
82
85
 
@@ -186,6 +189,9 @@ const structuredData = jsonLd({
186
189
  socials: config.socials,
187
190
  custom: seo.jsonLd,
188
191
  });
192
+ // The note that tells an AI agent reading this page where llms.txt is -
193
+ // see lib/agent-directive.js.
194
+ const agentNote = htmlDirective({ siteUrl, markdownPages: contextMenuOptions(config.contextMenu).length > 0 });
189
195
  // Analytics wait for the reader's answer when the consent banner is on -
190
196
  // see lib/consent.js.
191
197
  const consent = consentOptions(config.integrations.consent);
@@ -423,9 +429,8 @@ const publicJsHrefs = rootAssets.publicJs.filter((href) => !explicitScriptSrcs.h
423
429
  // below.
424
430
  const resolvedFonts = resolveFonts(config);
425
431
  const fontsGoogleHref = googleFontsHref(resolvedFonts);
426
- function fontStack(family: string): string {
427
- return `'${family}', -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
428
- }
432
+ // fontStack() and the stand-in font that keeps text from moving when the
433
+ // web font arrives are in lib/font-fallback.js.
429
434
  // heading/body already fall back to `resolvedFonts.base` right here (not
430
435
  // left as a CSS var() fallback chain for :root below to resolve) - same
431
436
  // "fully resolve in JS, plain values into define:vars" approach every
@@ -468,7 +473,12 @@ const fontWeightCss = [
468
473
  ]
469
474
  .filter(Boolean)
470
475
  .join("\n");
471
- const fontExtraCss = [fontFaceCss, fontWeightCss].filter(Boolean).join("\n");
476
+ // The stand-in for each font that has one (lib/font-fallback.js) - the
477
+ // stacks above already name it, right after the font itself.
478
+ const fontFallbackCss = fallbackFontFaces(
479
+ [resolvedFonts.base, resolvedFonts.heading, resolvedFonts.body].filter(Boolean).map((font) => font!.family),
480
+ );
481
+ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolean).join("\n");
472
482
  ---
473
483
 
474
484
  <!doctype html>
@@ -735,6 +745,15 @@ const fontExtraCss = [fontFaceCss, fontWeightCss].filter(Boolean).join("\n");
735
745
  {publicCssHrefs.map((href) => <link rel="stylesheet" href={href} />)}
736
746
  </head>
737
747
  <body>
748
+ {
749
+ /* For AI agents, first thing in the page: where the documentation index
750
+ is (lib/agent-directive.js). Not for people - hidden from sight
751
+ (.wd-agent-note, base.css) and from screen readers, its link out of
752
+ the tab order, and kept out of search snippets and the site's search. */
753
+ }
754
+ <div class="wd-agent-note" aria-hidden="true" data-nosnippet data-pagefind-ignore>
755
+ {agentNote.before}<a href={agentNote.href} tabindex="-1">{agentNote.link}</a>{agentNote.after}
756
+ </div>
738
757
  {
739
758
  mode === "blank" ? (
740
759
  // No site chrome at all - no topbar, no sidebar/toc columns, not
@@ -32,7 +32,7 @@ interface Props {
32
32
 
33
33
  const { items } = Astro.props as Props;
34
34
  ---
35
- <nav class="wd-breadcrumbs" aria-label="Breadcrumb" data-pagefind-ignore>
35
+ <nav class="wd-breadcrumbs" aria-label="Breadcrumb" data-pagefind-ignore data-markdown-ignore>
36
36
  <ol class="wd-breadcrumb-list">
37
37
  <li class="wd-breadcrumb-item">
38
38
  <a href="/" class="wd-breadcrumb-home" aria-label="Home">
@@ -31,6 +31,7 @@
31
31
  // comment for the fuller rationale.
32
32
  import { isExternalHref, type DocsConfig, type Selector, type GlobalDropdownView } from '../../lib/config';
33
33
  import AppIcon from '../../components/AppIcon.astro';
34
+ import { logoWidth } from '../../lib/image-size.js';
34
35
  import { hasMobileMenu, currentOption } from '../../lib/selector-placement.js';
35
36
  import '../styles/dropdown.css';
36
37
  import '../styles/topbar.css';
@@ -82,8 +83,8 @@ const showMenu = hasMobileMenu({ sidebar: showSidebarCol, selectors, globalDropd
82
83
  </svg>
83
84
  </button>
84
85
  <a class="wd-topbar-brand" href="/">
85
- {logoLight && <img src={logoLight} alt={config.name} height="24" class="wd-logo-light" />}
86
- {logoDark && <img src={logoDark} alt={config.name} height="24" class="wd-logo-dark" />}
86
+ {logoLight && <img src={logoLight} alt={config.name} height="24" width={logoWidth(logoLight)} class="wd-logo-light" />}
87
+ {logoDark && <img src={logoDark} alt={config.name} height="24" width={logoWidth(logoDark)} class="wd-logo-dark" />}
87
88
  {brandLabel && <span>{brandLabel}</span>}
88
89
  </a>
89
90
  {/* Same class as the real topbar's own theme button -
@@ -81,8 +81,8 @@ const { navTree, hrefForSlug, currentSlug, switchers = [] } = Astro.props as Pro
81
81
  <NavTree nodes={navTree} hrefForSlug={hrefForSlug} currentSlug={currentSlug} />
82
82
  {!watermarkDisabled && (
83
83
  <div class="wd-sidebar-watermark">
84
- <img src={watermarkForLightTheme.src} alt="Powered by writedocs" class="wd-watermark-light" />
85
- <img src={watermarkForDarkTheme.src} alt="Powered by writedocs" class="wd-watermark-dark" />
84
+ <img src={watermarkForLightTheme.src} alt="Powered by writedocs" class="wd-watermark-light" width={watermarkForLightTheme.width} height={watermarkForLightTheme.height} loading="lazy" decoding="async" />
85
+ <img src={watermarkForDarkTheme.src} alt="Powered by writedocs" class="wd-watermark-dark" width={watermarkForDarkTheme.width} height={watermarkForDarkTheme.height} loading="lazy" decoding="async" />
86
86
  </div>
87
87
  )}
88
88
  </nav>
@@ -11,6 +11,7 @@
11
11
  // comment for the fuller rationale.
12
12
  import { isExternalHref, type DocsConfig } from '../../lib/config';
13
13
  import AppIcon from '../../components/AppIcon.astro';
14
+ import { logoWidth } from '../../lib/image-size.js';
14
15
  import '../styles/footer.css';
15
16
 
16
17
  interface Props {
@@ -37,8 +38,8 @@ const hasFooterContent = config.footer.columns.length > 0 || socialEntries.lengt
37
38
  <div class="wd-footer-inner">
38
39
  {hasLogoImage && (
39
40
  <a class="wd-footer-brand" href="/">
40
- {logoLight && <img src={logoLight} alt={config.name} height="24" class="wd-logo-light" />}
41
- {logoDark && <img src={logoDark} alt={config.name} height="24" class="wd-logo-dark" />}
41
+ {logoLight && <img src={logoLight} alt={config.name} height="24" width={logoWidth(logoLight)} class="wd-logo-light" />}
42
+ {logoDark && <img src={logoDark} alt={config.name} height="24" width={logoWidth(logoDark)} class="wd-logo-dark" />}
42
43
  </a>
43
44
  )}
44
45
  {config.footer.columns.length > 0 && (
@@ -13,6 +13,7 @@
13
13
  // comment for the fuller rationale.
14
14
  import { isExternalHref, type DocsConfig, type Selector, type GlobalDropdownView } from '../../lib/config';
15
15
  import AppIcon from '../../components/AppIcon.astro';
16
+ import { logoWidth } from '../../lib/image-size.js';
16
17
  import { selectorPlacements, hasMobileMenu, currentOption } from '../../lib/selector-placement.js';
17
18
  import '../styles/dropdown.css';
18
19
  import '../styles/topbar.css';
@@ -92,8 +93,8 @@ const tabRows = tabSelectors.length > 0 ? tabSelectors : globalDropdowns.length
92
93
  </button>
93
94
  )}
94
95
  <a class="wd-topbar-brand" href="/">
95
- {logoLight && <img src={logoLight} alt={config.name} height="24" class="wd-logo-light" />}
96
- {logoDark && <img src={logoDark} alt={config.name} height="24" class="wd-logo-dark" />}
96
+ {logoLight && <img src={logoLight} alt={config.name} height="24" width={logoWidth(logoLight)} class="wd-logo-light" />}
97
+ {logoDark && <img src={logoDark} alt={config.name} height="24" width={logoWidth(logoDark)} class="wd-logo-dark" />}
97
98
  {brandLabel && <span title={brandLabel}>{brandLabel}</span>}
98
99
  </a>
99
100
 
@@ -250,6 +250,28 @@ pre {
250
250
  it loads, and this keeps its height following its width when it's shown
251
251
  narrower than the file - without it, the height attribute would stretch
252
252
  it. :where() adds no specificity, so any rule that sets a height wins. */
253
+ /* The note for AI agents at the top of every page (lib/agent-directive.js):
254
+ in the HTML, where an agent reads it, and out of sight. Clipped rather
255
+ than display: none, which HTML-to-text converters often drop. */
256
+ .wd-agent-note {
257
+ position: absolute;
258
+ width: 1px;
259
+ height: 1px;
260
+ margin: -1px;
261
+ padding: 0;
262
+ overflow: hidden;
263
+ clip: rect(0 0 0 0);
264
+ clip-path: inset(50%);
265
+ white-space: nowrap;
266
+ border: 0;
267
+ }
268
+ /* The logo has a width beside its height (logoWidth(), lib/image-size.js)
269
+ so its place is kept while it loads. `width: auto` lets a site's own CSS
270
+ change its height without squeezing it - the two attributes still tell
271
+ the browser its proportions. */
272
+ :where(.wd-logo-light, .wd-logo-dark) {
273
+ width: auto;
274
+ }
253
275
  :where(img[data-wd-sized]) {
254
276
  height: auto;
255
277
  }
@@ -0,0 +1,47 @@
1
+ // Telling an AI agent where the documentation index is. An agent that
2
+ // lands on one page - its HTML, or its Markdown copy - has no way to know
3
+ // the site has an llms.txt listing every page, or that each page has a
4
+ // Markdown version, unless the page says so. Two short notes do:
5
+ //
6
+ // - in every HTML page, a line at the very top of <body>, hidden from
7
+ // sight and from screen readers (BaseLayout.astro, .wd-agent-note in
8
+ // base.css) - an agent reading the HTML meets it before the navigation;
9
+ // - in every page's Markdown copy, a blockquote under the title
10
+ // (src/pages/[...slug].md.ts).
11
+ //
12
+ // A third convention lives in the components, not here: an element of a
13
+ // page that isn't content but sits inside the content area - the "Copy
14
+ // page" menu, the breadcrumbs, the "#" link beside a title, previous/next -
15
+ // carries `data-markdown-ignore`. The Markdown copy has none of them, and
16
+ // the attribute tells a tool comparing the two that this is on purpose.
17
+ //
18
+ // Plain JavaScript, for scripts/agent-directive.test.js.
19
+
20
+ /** The index's address: a full URL with a `domain`, else from the site's root. */
21
+ export function llmsIndexUrl(siteUrl) {
22
+ return siteUrl ? `${siteUrl}/llms.txt` : '/llms.txt';
23
+ }
24
+
25
+ /** The note for an HTML page: `{ href, before, link, after }` - the text
26
+ * around the link to llms.txt. `markdownPages` says whether pages have a
27
+ * Markdown copy (off with `"contextMenu": false`). */
28
+ export function htmlDirective({ siteUrl = null, markdownPages = true } = {}) {
29
+ return {
30
+ href: llmsIndexUrl(siteUrl),
31
+ before: 'For AI agents: the documentation index is at ',
32
+ link: '/llms.txt',
33
+ after: markdownPages ? '. A Markdown version of every page is available by adding .md to its address.' : '.',
34
+ };
35
+ }
36
+
37
+ /** The note for a page's Markdown copy, as a blockquote. */
38
+ export function markdownDirective(siteUrl = null) {
39
+ return `> For the complete documentation index, see [llms.txt](${llmsIndexUrl(siteUrl)}).`;
40
+ }
41
+
42
+ /** A page's Markdown copy: its title, the note, its description - the line
43
+ * the page shows under its title - then its content. */
44
+ export function pageMarkdownDocument(title, body, siteUrl = null, description = undefined) {
45
+ const intro = typeof description === 'string' && description.trim() ? `${description.trim()}\n\n` : '';
46
+ return `# ${title}\n\n${markdownDirective(siteUrl)}\n\n${intro}${body}`;
47
+ }
@@ -12,6 +12,7 @@ import fs from 'node:fs';
12
12
  import path from 'node:path';
13
13
  import matter from 'gray-matter';
14
14
  import { applyVisibilityForAgents } from './visibility.js';
15
+ import { componentsToMarkdown } from './components-to-markdown.js';
15
16
 
16
17
  /** `text` with `transform` applied to everything outside fenced code blocks
17
18
  * and inline code spans; code comes back untouched. */
@@ -43,7 +44,9 @@ export function mapOutsideCode(text, transform) {
43
44
  function mapOutsideInlineCode(text, transform) {
44
45
  // Backtick runs of equal length delimit a code span (CommonMark).
45
46
  return text
46
- .split(/(`+)([\s\S]*?)(\1)(?!`)/)
47
+ // A closing run is a whole run: in "` ```bash `" the three backticks
48
+ // inside don't close the span that one backtick opened.
49
+ .split(/(?<!`)(`+)(?!`)([\s\S]*?)(?<!`)(\1)(?!`)/)
47
50
  .reduce((acc, part, i, parts) => {
48
51
  const k = i % 4;
49
52
  if (k === 0) acc.push(transform(part));
@@ -133,10 +136,27 @@ export function inlineSnippets(text, { file, contentDir, depth = 0 }) {
133
136
  return result.replace(/\n{3,}/g, '\n\n');
134
137
  }
135
138
 
139
+ /** Links and images written from the site's root (`/docs/setup/`) as full
140
+ * URLs. A page copied out of the site - pasted into a chat, fetched by an
141
+ * agent, read from llms-full.txt - has no site to resolve them against.
142
+ * Markdown links and images, and the `href`/`src`/`img` of a component;
143
+ * code is left as written, and so is everything without a `siteUrl`. */
144
+ export function absolutizeLinks(text, siteUrl) {
145
+ if (!siteUrl) return text;
146
+ return mapOutsideCode(text, (prose) =>
147
+ prose
148
+ .replace(/(\]\()\/(?!\/)/g, `$1${siteUrl}/`)
149
+ .replace(/(\b(?:href|src|img)=["'])\/(?!\/)/g, `$1${siteUrl}/`)
150
+ );
151
+ }
152
+
136
153
  /** A page's body as an agent should read it. `file` is the page's absolute
137
154
  * path (to resolve relative snippet imports). */
138
155
  export function markdownForAgents(body, { file, contentDir, variables }) {
139
156
  let text = applyVisibilityForAgents(body ?? '');
140
157
  if (file) text = inlineSnippets(text, { file, contentDir });
141
- return substituteVariables(text, variables);
158
+ text = substituteVariables(text, variables);
159
+ // Components as the Markdown that says what they show
160
+ // (lib/components-to-markdown.js) - in an .mdx page; a .md page has none.
161
+ return file && /\.md$/i.test(file) ? text : componentsToMarkdown(text);
142
162
  }
@@ -0,0 +1,297 @@
1
+ // A page's components, written as Markdown - for the text an AI agent reads
2
+ // (a page's .md copy, llms-full.txt, the MCP server).
3
+ //
4
+ // A page's source keeps its components as tags, and what a component shows
5
+ // from its attributes is then not text at all:
6
+ //
7
+ // <Parameter name="amount" type="integer" required> -> **`amount`** `integer` required
8
+ // The amount to charge.
9
+ // </Parameter> The amount to charge.
10
+ //
11
+ // An agent reading the tags has to guess what the page looks like; one
12
+ // comparing the copy with the page finds a third of a reference page
13
+ // missing. So each component writedocs knows is replaced by the Markdown
14
+ // that says what it shows: its title, labels and caption as text, its
15
+ // content where it was - no longer indented under a tag, which Markdown
16
+ // would read as a code block.
17
+ //
18
+ // Comments in the source - {/* ... */} - are dropped on the way: the page
19
+ // doesn't show them, and they are often notes not meant for readers. Before
20
+ // this, a page's copy, llms-full.txt and the MCP server all published them.
21
+ //
22
+ // How: the page is parsed as MDX only to find the components; the output is
23
+ // stitched from the page's own source text, so everything that isn't one of
24
+ // these components - prose, code, tables, a site's own snippet components -
25
+ // comes back exactly as written. A page that doesn't parse is returned
26
+ // untouched.
27
+ //
28
+ // Plain JavaScript, for scripts/components-to-markdown.test.js.
29
+ import { createProcessor } from '@mdx-js/mdx';
30
+
31
+ let processor = null;
32
+ function parseMdx(text) {
33
+ processor ??= createProcessor({ format: 'mdx' });
34
+ return processor.parse(text);
35
+ }
36
+
37
+ const isJsx = (node) => node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement';
38
+ /** An expression holding nothing but comments: `{/* draft - check with legal *\/}`. */
39
+ const isComment = (node) =>
40
+ (node.type === 'mdxFlowExpression' || node.type === 'mdxTextExpression') && /^\s*(\/\*[\s\S]*?\*\/\s*)+$/.test(node.value ?? '');
41
+
42
+ /** Markup in a title written as JSX (`{<><code>X</code> details</>}`) as text. */
43
+ const stripTags = (text) => text.replace(/<\/?[A-Za-z][^>]*>|<\/?>/g, '');
44
+
45
+ /** An attribute's value as text: a string as it is, `{4}`/`{"x"}`/`{true}` as
46
+ * their value, a bare attribute as true; undefined when absent. */
47
+ function attr(node, name) {
48
+ const attribute = node.attributes?.find((a) => a.type === 'mdxJsxAttribute' && a.name === name);
49
+ if (!attribute) return undefined;
50
+ if (attribute.value === null || attribute.value === undefined) return true;
51
+ if (typeof attribute.value === 'string') return attribute.value;
52
+ const raw = String(attribute.value.value ?? '').trim();
53
+ if (raw === 'true') return true;
54
+ if (raw === 'false') return false;
55
+ const quoted = raw.match(/^(["'`])([\s\S]*)\1$/);
56
+ if (quoted) return quoted[2];
57
+ return stripTags(raw).trim();
58
+ }
59
+
60
+ /** A list attribute - `pre={["read-only"]}` - as its items. */
61
+ function listAttr(node, name) {
62
+ const value = attr(node, name);
63
+ if (typeof value !== 'string') return [];
64
+ return [...value.matchAll(/(["'`])((?:(?!\1).)*)\1/g)].map((m) => m[2]);
65
+ }
66
+
67
+ const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : '');
68
+ const on = (value) => value === true || value === 'true' || value === '';
69
+ const code = (value) => `\`${String(value).replace(/`/g, "'")}\``;
70
+ const blocks = (...parts) => parts.filter((part) => part && part.trim()).join('\n\n');
71
+ const quote = (body) =>
72
+ body
73
+ .split('\n')
74
+ .map((line) => (line ? `> ${line}` : '>'))
75
+ .join('\n');
76
+
77
+ /** A field of a reference: its name, type and labels on one line, in the
78
+ * order the page shows them, then what it says. */
79
+ function parameter(node, body) {
80
+ // ParamField names the field by where it goes: path="id", query="limit"...
81
+ const place = ['path', 'query', 'body', 'header'].find((key) => text(attr(node, key)));
82
+ const name = text(attr(node, 'name')) || (place ? text(attr(node, place)) : '');
83
+ const head = [
84
+ ...listAttr(node, 'pre'),
85
+ name && `**${code(name)}**`,
86
+ text(attr(node, 'type')) && code(attr(node, 'type')),
87
+ on(attr(node, 'required')) && 'required',
88
+ on(attr(node, 'deprecated')) && 'deprecated',
89
+ ...listAttr(node, 'post'),
90
+ attr(node, 'default') !== undefined && attr(node, 'default') !== '' && `default: ${code(attr(node, 'default'))}`,
91
+ ].filter(Boolean);
92
+ return blocks(head.join(' '), body);
93
+ }
94
+
95
+ const titled = (node, body, extra) => blocks(text(attr(node, 'title')) && `**${text(attr(node, 'title'))}**`, extra, body);
96
+ const unwrap = (node, body) => body;
97
+
98
+ function callout(label) {
99
+ return (node, body) => {
100
+ const title = text(attr(node, 'title')) || label;
101
+ return quote(blocks(title && `**${title}**`, body));
102
+ };
103
+ }
104
+
105
+ function card(node, body) {
106
+ const title = text(attr(node, 'title'));
107
+ const href = text(attr(node, 'href'));
108
+ const heading = title ? (href ? `**[${title}](${href})**` : `**${title}**`) : href ? `[${href}](${href})` : '';
109
+ return blocks(heading, text(attr(node, 'description')), body);
110
+ }
111
+
112
+ /** Component name -> (node, its content as Markdown, context) -> Markdown.
113
+ * A component that isn't here keeps its tags. */
114
+ const RENDERERS = {
115
+ Parameter: parameter,
116
+ ParamField: parameter,
117
+ ResponseField: parameter,
118
+ Expandable: (node, body) => titled(node, body),
119
+ Accordion: (node, body) => titled(node, body, text(attr(node, 'description'))),
120
+ AccordionGroup: unwrap,
121
+ Steps: unwrap,
122
+ Step: (node, body, context) => {
123
+ const title = text(attr(node, 'title'));
124
+ // `stepNumber` restarts the count, as on the page.
125
+ const number = Number(attr(node, 'stepNumber'));
126
+ if (Number.isFinite(number) && number > 0) context.offset.value = number - 1 - context.index;
127
+ return blocks(`**${context.index + 1 + context.offset.value}.${title ? ` ${title}` : ''}**`, body);
128
+ },
129
+ Tabs: unwrap,
130
+ Tab: (node, body) => titled(node, body),
131
+ View: (node, body) => titled(node, body),
132
+ CodeGroup: unwrap,
133
+ CardGroup: unwrap,
134
+ Columns: unwrap,
135
+ Column: unwrap,
136
+ Panel: unwrap,
137
+ Searchbar: unwrap,
138
+ RequestExample: unwrap,
139
+ ResponseExample: unwrap,
140
+ Callout: callout(''),
141
+ Note: callout('Note'),
142
+ Info: callout('Info'),
143
+ Tip: callout('Tip'),
144
+ Warning: callout('Warning'),
145
+ Danger: callout('Danger'),
146
+ Check: callout(''),
147
+ Card: card,
148
+ Tile: card,
149
+ Update: (node, body) => blocks(text(attr(node, 'label')) && `**${text(attr(node, 'label'))}**`, text(attr(node, 'description')), body),
150
+ Frame: (node, body) => blocks(body, text(attr(node, 'caption')) && `*${text(attr(node, 'caption'))}*`),
151
+ Image: (node) => {
152
+ const src = text(attr(node, 'src'));
153
+ if (!src) return null;
154
+ return blocks(`![${text(attr(node, 'alt'))}](${src})`, text(attr(node, 'caption')) && `*${text(attr(node, 'caption'))}*`);
155
+ },
156
+ // Inline ones: what they wrap, as text.
157
+ Badge: unwrap,
158
+ Tooltip: (node, body) => (text(attr(node, 'tip')) ? `${body} (${text(attr(node, 'tip'))})` : body),
159
+ Hint: (node, body) => {
160
+ const note = [text(attr(node, 'headline')), text(attr(node, 'tip'))].filter(Boolean).join(': ');
161
+ const link = text(attr(node, 'cta')) && text(attr(node, 'href')) ? `[${text(attr(node, 'cta'))}](${text(attr(node, 'href'))})` : '';
162
+ const aside = [note, link].filter(Boolean).join(' ');
163
+ return aside ? `${body} (${aside})` : body;
164
+ },
165
+ Icon: () => '',
166
+ };
167
+
168
+ /** Written inside a sentence; every other one is a block of its own, even
169
+ * when its tags sit on one line (`<Step title="Go">Run it.</Step>`, which
170
+ * MDX reads as part of a paragraph). */
171
+ const INLINE = new Set(['Badge', 'Tooltip', 'Hint', 'Icon']);
172
+
173
+ /** The components that become Markdown. */
174
+ export const CONVERTED_COMPONENTS = Object.keys(RENDERERS);
175
+
176
+ function dedent(value) {
177
+ const lines = value.replace(/^[ \t]*\n+/, '').replace(/\s+$/, '').split('\n');
178
+ const indents = lines.filter((line) => line.trim()).map((line) => line.match(/^[ \t]*/)[0].length);
179
+ const min = indents.length ? Math.min(...indents) : 0;
180
+ return lines.map((line) => line.slice(min)).join('\n');
181
+ }
182
+
183
+ /** Where an element's opening tag ends: its first `>` outside quotes and
184
+ * `{...}` - an attribute can hold either. */
185
+ function openingTagEnd(source, start) {
186
+ let depth = 0;
187
+ let quoteChar = null;
188
+ for (let i = start; i < source.length; i++) {
189
+ const c = source[i];
190
+ if (quoteChar) {
191
+ if (c === quoteChar) quoteChar = null;
192
+ } else if (depth === 0 && (c === '"' || c === "'")) quoteChar = c;
193
+ else if (c === '{') depth++;
194
+ else if (c === '}') depth--;
195
+ else if (c === '>' && depth === 0) return i + 1;
196
+ }
197
+ return -1;
198
+ }
199
+
200
+ /** Runs of blank lines as one - unwrapped groups leave them behind. Code
201
+ * blocks keep theirs: blank lines there are part of the example. */
202
+ function collapseBlankLines(value) {
203
+ const out = [];
204
+ let fence = null;
205
+ for (const line of value.split('\n')) {
206
+ const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
207
+ if (fence) {
208
+ if (marker && marker[0] === fence[0] && marker.length >= fence.length && line.trim() === marker) fence = null;
209
+ } else if (marker) fence = marker;
210
+ else if (!line.trim() && out.length && !out[out.length - 1].trim()) continue;
211
+ out.push(line);
212
+ }
213
+ return out.join('\n');
214
+ }
215
+
216
+ /** `source` with every known component replaced by its Markdown. */
217
+ export function componentsToMarkdown(source) {
218
+ if (typeof source !== 'string' || !/<[A-Z]|\{\s*\/\*/.test(source)) return source;
219
+ let tree;
220
+ try {
221
+ tree = parseMdx(source);
222
+ } catch {
223
+ return source; // not valid MDX - the build reports it; the copy stays as written
224
+ }
225
+
226
+ /** The source between two offsets, each known component in it replaced. */
227
+ const stitch = (nodes, from, to) => {
228
+ let out = '';
229
+ let at = from;
230
+ const visit = (list) => {
231
+ const counts = {};
232
+ const offset = { value: 0 };
233
+ for (const node of list) {
234
+ const start = node.position?.start?.offset;
235
+ const end = node.position?.end?.offset;
236
+ // A comment - {/* ... */} - is a note to whoever edits the page. The
237
+ // page doesn't show it, and neither does the copy.
238
+ if (isComment(node) && start !== undefined && start >= at && end <= to) {
239
+ out += source.slice(at, start);
240
+ at = end;
241
+ continue;
242
+ }
243
+ if (isJsx(node) && node.name && RENDERERS[node.name] && start !== undefined && start >= at && end <= to) {
244
+ const index = (counts[node.name] = (counts[node.name] ?? -1) + 1);
245
+ const rendered = render(node, { index, offset });
246
+ if (rendered !== null) {
247
+ // A flow element starts after its line's indentation; every line
248
+ // of what replaces it gets the same, so the whole block still
249
+ // dedents together with its siblings.
250
+ const lineStart = source.lastIndexOf('\n', start - 1) + 1;
251
+ const indent = /^[ \t]*$/.test(source.slice(lineStart, start)) ? source.slice(lineStart, start) : '';
252
+ let before = out + source.slice(at, start);
253
+ // Blank lines stay empty - no trailing indentation.
254
+ let block = rendered
255
+ .split('\n')
256
+ .map((line, i) => (i && line ? indent + line : line))
257
+ .join('\n');
258
+ if (!INLINE.has(node.name) && rendered) {
259
+ // Two components in a row, written with no blank line between
260
+ // their tags, are still two blocks of Markdown.
261
+ if (before.trim() && !/\n[ \t]*\n[ \t]*$/.test(before)) {
262
+ before = before.replace(/[ \t]+$/, '');
263
+ block = `\n${indent}${block}`;
264
+ }
265
+ const after = source.slice(end, to);
266
+ if (after.trim() && !/^[ \t]*\n[ \t]*\n/.test(after)) block += '\n';
267
+ }
268
+ out = before + block;
269
+ at = end;
270
+ continue;
271
+ }
272
+ }
273
+ if (Array.isArray(node.children)) visit(node.children);
274
+ }
275
+ };
276
+ visit(nodes);
277
+ return out + source.slice(at, to);
278
+ };
279
+
280
+ const render = (node, context) => {
281
+ const start = node.position.start.offset;
282
+ const end = node.position.end.offset;
283
+ const openEnd = openingTagEnd(source, start);
284
+ if (openEnd === -1) return null;
285
+ const selfClosing = source[openEnd - 2] === '/' || openEnd >= end;
286
+ let body = '';
287
+ if (!selfClosing) {
288
+ const closeStart = source.lastIndexOf('</', end);
289
+ if (closeStart < openEnd) return null;
290
+ const inner = stitch(node.children ?? [], openEnd, closeStart);
291
+ body = INLINE.has(node.name) ? inner.trim() : dedent(inner);
292
+ }
293
+ return RENDERERS[node.name](node, body, context);
294
+ };
295
+
296
+ return collapseBlankLines(stitch(tree.children, 0, source.length));
297
+ }
@@ -0,0 +1,79 @@
1
+ // A site's font stack, and the stand-in shown until its web font arrives.
2
+ //
3
+ // A web font loads after the page's text is on screen (`font-display:
4
+ // swap`), in whatever font comes next in the stack. When the web font
5
+ // arrives, every line is laid out again - and if the two fonts set text at
6
+ // different widths, paragraphs gain or lose a line and everything below
7
+ // them moves. That's layout shift (CLS): 0.06 on Windows for the default
8
+ // font, far more where the system's fallback is a wider one.
9
+ //
10
+ // The fix is a second @font-face that points at a font every system has
11
+ // (Arial, or its metric-compatible stand-ins on Linux and Android) and
12
+ // scales it to the web font's own proportions - `size-adjust` for the width
13
+ // of its letters, the `*-override`s for its line height. Text then takes
14
+ // the same space before and after the swap, and nothing moves.
15
+ //
16
+ // Each font needs its own numbers, so this covers the fonts in
17
+ // FALLBACK_METRICS - the default, Inter, first of all. Any other font
18
+ // keeps the plain system stack, as before.
19
+ //
20
+ // Plain JavaScript, for scripts/font-fallback.test.js.
21
+
22
+ /** Per web font (lower-cased family): how Arial has to be adjusted to take
23
+ * the same space, in percent.
24
+ * sizeAdjust - the web font's average letter width over Arial's.
25
+ * ascent/descent/lineGap - the web font's own vertical metrics, divided
26
+ * by sizeAdjust (the overrides apply after the scaling).
27
+ * Inter's come from its font file (unitsPerEm 2048, ascender 1984,
28
+ * descender -494, line gap 0), with the width ratio the build's browser
29
+ * check confirms to within 1% - see docs/dev/docs/site-config.mdx for how
30
+ * to measure a new font before adding it here. */
31
+ export const FALLBACK_METRICS = {
32
+ inter: { sizeAdjust: 107.06, ascent: 90.49, descent: 22.56, lineGap: 0 },
33
+ };
34
+
35
+ /** Arial, then the fonts that stand in for it where it isn't installed -
36
+ * Liberation Sans and Arimo have Arial's exact metrics (Linux, ChromeOS,
37
+ * Android), so the same numbers hold. The first one found is used. */
38
+ const LOCAL_FONTS = ['Arial', 'Liberation Sans', 'Arimo'].map((name) => `local('${name}')`).join(', ');
39
+
40
+ const metricsFor = (family) => FALLBACK_METRICS[String(family ?? '').trim().toLowerCase()] ?? null;
41
+
42
+ /** The stand-in's family name for `family` ("Inter Fallback"), or null when
43
+ * there are no numbers for that font. */
44
+ export function fallbackFontName(family) {
45
+ return metricsFor(family) ? `${String(family).trim()} Fallback` : null;
46
+ }
47
+
48
+ /** The stand-in's @font-face rule, or '' for a font with no numbers. */
49
+ export function fallbackFontFace(family) {
50
+ const metrics = metricsFor(family);
51
+ if (!metrics) return '';
52
+ return (
53
+ `@font-face { font-family: '${fallbackFontName(family)}'; src: ${LOCAL_FONTS}; ` +
54
+ `size-adjust: ${metrics.sizeAdjust}%; ascent-override: ${metrics.ascent}%; ` +
55
+ `descent-override: ${metrics.descent}%; line-gap-override: ${metrics.lineGap}%; }`
56
+ );
57
+ }
58
+
59
+ /** The `font-family` value for `family`: the font, its stand-in when it has
60
+ * one, then the system fonts. */
61
+ export function fontStack(family) {
62
+ const fallback = fallbackFontName(family);
63
+ return `'${family}', ${fallback ? `'${fallback}', ` : ''}-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
64
+ }
65
+
66
+ /** The stand-in rules for a set of families, one per font that has numbers,
67
+ * without repeats. */
68
+ export function fallbackFontFaces(families) {
69
+ const seen = new Set();
70
+ return families
71
+ .filter((family) => {
72
+ const name = fallbackFontName(family);
73
+ if (!name || seen.has(name)) return false;
74
+ seen.add(name);
75
+ return true;
76
+ })
77
+ .map(fallbackFontFace)
78
+ .join('\n');
79
+ }
@@ -107,6 +107,16 @@ export function imageSize(file) {
107
107
  return size;
108
108
  }
109
109
 
110
+ /** The width a logo takes at `height` pixels tall, from its file's own
111
+ * proportions - written on the <img> beside its height, so the browser
112
+ * keeps the logo's place before it loads. Undefined when the file isn't
113
+ * in the project or can't be read: the image is then left as it was. */
114
+ export function logoWidth(src, height = 24, contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd()) {
115
+ const file = imageFileFor(src, contentDir);
116
+ const size = file && imageSize(file);
117
+ return size ? Math.round((size.width / size.height) * height) : undefined;
118
+ }
119
+
110
120
  /** The file behind a root-relative image address ("/images/a.png"): in
111
121
  * public/, or anywhere in the project - where the build finds it too
112
122
  * (lib/styles-asset-integration.js). Null for any other address. */
@@ -79,7 +79,7 @@ export async function mcpIndex(): Promise<McpIndex> {
79
79
  const fileId = fileIdForEntry(contentDir, packageRoot, entry);
80
80
  // An API page's source is a near-empty stub - its operation, written
81
81
  // out from the spec, follows its own text (lib/openapi-markdown.ts).
82
- const content = pageMarkdown(entry, { contentDir, packageRoot, variables: config.variables });
82
+ const content = pageMarkdown(entry, { contentDir, packageRoot, variables: config.variables, siteUrl: siteUrl || null });
83
83
  return {
84
84
  slug,
85
85
  fileId,
@@ -22,7 +22,7 @@ import {
22
22
  type SchemaRow,
23
23
  } from './openapi-render';
24
24
  import { parseOpenApiRef } from './openapi-ref.js';
25
- import { markdownForAgents } from './agent-markdown.js';
25
+ import { markdownForAgents, absolutizeLinks } from './agent-markdown.js';
26
26
 
27
27
  let renderer: ReturnType<typeof createMarkdownProcessor> | null = null;
28
28
  const htmlCache = new Map<string, Promise<string>>();
@@ -140,13 +140,23 @@ interface PageEntry {
140
140
  * after it - in the order the page shows them. */
141
141
  export function pageMarkdown(
142
142
  entry: PageEntry,
143
- { contentDir, packageRoot, variables }: { contentDir: string; packageRoot: string; variables: Record<string, string> }
144
- ): string {
145
- const own = markdownForAgents(entry.body ?? '', {
146
- file: entry.filePath ? path.resolve(packageRoot, entry.filePath) : undefined,
143
+ {
147
144
  contentDir,
145
+ packageRoot,
148
146
  variables,
149
- }).trim();
147
+ siteUrl = null,
148
+ }: { contentDir: string; packageRoot: string; variables: Record<string, string>; siteUrl?: string | null }
149
+ ): string {
150
+ // Root-relative links become full URLs when the site has a `domain` -
151
+ // this text is read away from the site (absolutizeLinks()).
152
+ const own = absolutizeLinks(
153
+ markdownForAgents(entry.body ?? '', {
154
+ file: entry.filePath ? path.resolve(packageRoot, entry.filePath) : undefined,
155
+ contentDir,
156
+ variables,
157
+ }),
158
+ siteUrl
159
+ ).trim();
150
160
  if (!entry.data.openapi) return own;
151
161
  const op = loadOperation(entry.data.openapi, contentDir);
152
162
  const operation = op ? operationMarkdown(op) : `Operation: ${entry.data.openapi}`;
@@ -621,7 +621,7 @@ const components = {
621
621
  {entry.data.openapi && <ApiPlayground operation={entry.data.openapi} contentDir={contentDir} />}
622
622
  {/* After the content: a result's excerpt shows the section only when
623
623
  that's what matched. */}
624
- <div hidden data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
624
+ <div hidden data-markdown-ignore data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
625
625
  {pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
626
626
  </div>
627
627
  </div>
@@ -647,11 +647,11 @@ const components = {
647
647
  </div>
648
648
  <Content components={components} />
649
649
  {entry.data.openapi && <ApiPlayground operation={entry.data.openapi} contentDir={contentDir} />}
650
- <div hidden data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
650
+ <div hidden data-markdown-ignore data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
651
651
  {pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
652
652
  </div>
653
653
  {!entry.data.hideFooterPagination && (
654
- <nav class="wd-prevnext" data-pagefind-ignore>
654
+ <nav class="wd-prevnext" data-pagefind-ignore data-markdown-ignore>
655
655
  {prev && (
656
656
  <a class="wd-prevnext-card wd-prevnext-prev" href={hrefForSlug(prev.slug)}>
657
657
  <span class="wd-prevnext-row">
@@ -2,7 +2,8 @@ import { getCollection, type CollectionEntry } from 'astro:content';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import type { APIRoute } from 'astro';
5
- import { loadDocsConfig, normalizeEntryId, findAllPages, contextMenuOptions } from '../lib/config';
5
+ import { loadDocsConfig, normalizeEntryId, findAllPages, contextMenuOptions, resolveSiteUrl } from '../lib/config';
6
+ import { pageMarkdownDocument } from '../lib/agent-directive.js';
6
7
  import { writedocsTempDir } from '../lib/writedocs-temp-dir.js';
7
8
  import { pageMarkdown } from '../lib/openapi-markdown';
8
9
 
@@ -52,17 +53,18 @@ export async function getStaticPaths() {
52
53
  .map((entry) => ({
53
54
  params: { slug: normalizeEntryId(entry.id) },
54
55
  // Passed along rather than re-read per page - GET only renders one entry.
55
- props: { entry, variables: config.variables },
56
+ props: { entry, variables: config.variables, siteUrl: resolveSiteUrl(config) },
56
57
  }));
57
58
  }
58
59
 
59
60
  interface Props {
60
61
  entry: DocsEntry;
61
62
  variables: Record<string, string>;
63
+ siteUrl: string | null;
62
64
  }
63
65
 
64
66
  export const GET: APIRoute = ({ props }) => {
65
- const { entry, variables } = props as Props;
67
+ const { entry, variables, siteUrl } = props as Props;
66
68
  const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
67
69
  const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
68
70
  // entry.body is the raw, frontmatter-stripped MDX/Markdown source text
@@ -75,8 +77,16 @@ export const GET: APIRoute = ({ props }) => {
75
77
  // for agents, imported snippets inlined, `variables` filled in - see
76
78
  // lib/agent-markdown.js (llms-full.txt uses the same).
77
79
  // An API page's operation is written out after its own text (lib/openapi-markdown.ts).
78
- const body = pageMarkdown(entry, { contentDir, packageRoot, variables });
79
- const markdown = `# ${entry.data.title}\n\n${body}`;
80
+ const body = pageMarkdown(entry, { contentDir, packageRoot, variables, siteUrl });
81
+ // The title, a line pointing an agent at llms.txt, the page's description, then the page
82
+ // (lib/agent-directive.js).
83
+ const markdown = pageMarkdownDocument(
84
+ entry.data.title,
85
+ body,
86
+ siteUrl,
87
+ // An API page's description is the operation's, which the body already has.
88
+ entry.data.openapi ? undefined : entry.data.description
89
+ );
80
90
  return new Response(markdown, {
81
91
  headers: { 'Content-Type': 'text/markdown; charset=utf-8' },
82
92
  });
@@ -54,7 +54,7 @@ export const GET: APIRoute = async () => {
54
54
  // imported snippets inlined, `variables` filled in - same as the .md
55
55
  // route (lib/agent-markdown.js).
56
56
  // An API page's operation is written out after its own text (lib/openapi-markdown.ts).
57
- const body = pageMarkdown(entry, { contentDir, packageRoot, variables: config.variables });
57
+ const body = pageMarkdown(entry, { contentDir, packageRoot, variables: config.variables, siteUrl });
58
58
  // The page's own URL, so an agent can cite it.
59
59
  const url = `${siteUrl ?? ''}${slug === 'index' ? '/' : `/${slug}/`}`;
60
60
  return {